/// <reference types="vitest" />
import path from 'path';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import svgr from 'vite-plugin-svgr';
import { internalIpV4 } from 'internal-ip';
import { configDotenv } from 'dotenv';

configDotenv();

const { SM_ENV_PORT, TAURI_ENV_PLATFORM, SM_MAPBOX_TOKEN, SM_GEOVIS_TOKEN, SM_APP_VERSION, SM_TIANDITU_TOKEN } = process.env;
const mobile = !!/android|ios/.exec(TAURI_ENV_PLATFORM ?? '');
const root = path.resolve(__dirname, 'src');
const port = +(SM_ENV_PORT ?? 3000);
const fileNameTemplate = '[name].[hash].[ext]';
const assetsDirName = 'static';
const imagesDirName = 'images';
const jsDirName = 'js';
const cssDirName = 'css';
const chunkFileNames = `${assetsDirName}/${jsDirName}/[name].[hash].js`;

export default defineConfig(async () => ({
  base: './',
  plugins: [react(), svgr({ include: '**/*.svg?react', svgrOptions: { icon: true } })].filter((_) => _),
  resolve: {
    alias: [
      { find: '@', replacement: root },
      { find: /^~/, replacement: '' },
    ],
  },
  define: {
    'import.meta.env.SM_MAPBOX_TOKEN': JSON.stringify(SM_MAPBOX_TOKEN),
    'import.meta.env.SM_APP_VERSION': JSON.stringify(SM_APP_VERSION),
    'import.meta.env.SM_TIANDITU_TOKEN': JSON.stringify(SM_TIANDITU_TOKEN),
    'import.meta.env.SM_GEOVIS_TOKEN': JSON.stringify(SM_GEOVIS_TOKEN),
  },
  clearScreen: false,
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
        modifyVars: {},
      },
      modules: {
        generateScopedName: '[local]-[hash:base64:5]',
        localsConvention: 'camelCaseOnly',
      },
    },
  },
  server: {
    port,
    strictPort: true,
    host: '0.0.0.0',
    hmr: mobile ? { protocol: 'ws', host: await internalIpV4(), port: 1421 } : undefined,
  },
  test: {
    include: ['**/__tests__/**/*.test.ts'],
    exclude: ['**/node_modules/**', '**/dist/**'],
    environment: 'happy-dom',
  },
  build: {
    outDir: path.resolve(__dirname, 'deploy', 'dist'),

    assetsDir: assetsDirName,
    rollupOptions: {
      output: {
        chunkFileNames,
        entryFileNames: chunkFileNames,
        // manualChunks: {
        // },
        assetFileNames: (chunkInfo: any) => {
          let subDir = imagesDirName;
          if (path.extname(chunkInfo.name) === '.css') {
            subDir = cssDirName;
          }
          return `${assetsDirName}/${subDir}/${fileNameTemplate}`;
        },
      },
    },
  },
}));
